﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Prism.Commands;
using System.Windows.Input;

namespace BBInterfaceNET.Events.Commands
{
    //By default a composite command can execute only if all of its active
    //commands can execute
    //this implementation overrides the CanExecute method in order to enable the 
    //composite command to execute if at least one of the registered commands can execute

    //NOTE: on view models that subscribe to this type of composite command the
    //execute handler sould call the canExecute handler first (if available)
    //because all commands will execute (even the ones that souldn't). The original 
    //implementation covered this by executing only when all commands could be executed.
    public class CustomCompositeCommand:CompositeCommand
    {
        public CustomCompositeCommand():base()
        {}
        public CustomCompositeCommand(bool monitorCommandActivity)
            : base(monitorCommandActivity)
        {}
        public override bool CanExecute(object parameter)
        {
            ICommand[] commandList;
            bool hasEnabledCommandsThatShouldBeExecuted = false;
            lock (this.RegisteredCommands)
            {
                commandList = this.RegisteredCommands.ToArray();
            }
            foreach (ICommand command in commandList)
            {
                if (this.ShouldExecute(command))
                {
                    if (command.CanExecute(parameter))
                    {
                        hasEnabledCommandsThatShouldBeExecuted = true;
                    }
                }
            }
            return hasEnabledCommandsThatShouldBeExecuted;
        }
    }
}
